package br.ufpe.cin.quickmall;

import java.util.List;

import org.json.JSONException;

import br.cin.ufpe.quickmall.facebook.FacebookLogin;
import br.cin.ufpe.quickmall.facebook.LoginButton;
import br.ufpe.cin.quickmall.exception.CommException;
import br.ufpe.cin.quickmall.store.Offer;
import br.ufpe.cin.quickmall.utils.OfferLoader;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class QuickMallActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        
        TextView aboutTextView = (TextView) findViewById(R.id.about_textview);
        aboutTextView.setOnClickListener(this);
        TextView offersTextView = (TextView) findViewById(R.id.see_offers_textview);
        offersTextView.setOnClickListener(this);
        TextView goToMap = (TextView) findViewById(R.id.go_to_map_textview);
        goToMap.setOnClickListener(this);
        LoginButton logoutButton = (LoginButton) findViewById(R.id.logout);
        logoutButton.setOnClickListener(this);
    }
    
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.about_textview:
			Toast.makeText(this, getString(R.string.about_text), Toast.LENGTH_LONG).show();
			break;
		case R.id.see_offers_textview:
			Toast.makeText(this, getString(R.string.wait_text), Toast.LENGTH_SHORT).show();
			Toast.makeText(this, this.getOffersText(), Toast.LENGTH_LONG).show();
			break;
		case R.id.go_to_map_textview:
			startActivity(new Intent(QuickMallActivity.this, MapActivity.class));
			finish();
			break;
		case R.id.logout:
			startActivity(new Intent(QuickMallActivity.this, FacebookLogin.class));
			finish();
			break;
		default:
			break;
		}
	}
    
	private String getOffersText () {
		
    	StringBuilder stringBuilder = new StringBuilder();
    	
    	try {
			List<Offer> offerList = OfferLoader.getAllOffers();
			
			for (Offer offer : offerList) {
	        	stringBuilder.append(offer.getStore().getName());
	        	stringBuilder.append("\n");
	        	stringBuilder.append(offer.getDescription());
	        	stringBuilder.append("\n");
	        	stringBuilder.append("__________________\n");
			}
	        
		} catch (CommException e) {
			stringBuilder.append("CommException");
		} catch (JSONException e) {
			//FIXME this can't be hardcoded
			stringBuilder.append("JSONException");
		}
        
        return stringBuilder.toString();
    }
	
	
}